package com.swiftops.common.util;

import com.swiftops.common.core.ApiResult;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 错误信息处理工具
 */
public class BindingResultUtil {
//    public static ResponseEntity<Result<Object>> getErrorMessage(BindingResult bindingResult) {
//        String errorMessage = "";
//        for (ObjectError objectError : bindingResult.getAllErrors()) {
//            errorMessage += objectError.getDefaultMessage();
//        }
//        return new ResponseEntity<>(Result.error(ResultCode.FAIL, errorMessage), HttpStatus.OK);
//    }

    public static ResponseEntity<ApiResult<Object>> getErrorMessage(BindingResult bindingResult) {
//        List<String> errorMessageList = bindingResult.getAllErrors().stream()
//                .map(ObjectError::getDefaultMessage)
//                .collect(Collectors.toList());

        List<String> errorMessageList = bindingResult.getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.toList());

        String errorMessage = String.join("，", errorMessageList);

        return ApiResult.error(400, errorMessage);
    }
}
